package cn.yuanqiao.cqbc.yqSetPlate.service.impl;

import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.cqbc.common.mapper.MapperToolsMapper;
import cn.yuanqiao.cqbc.dataManage.domain.DataManage;
import cn.yuanqiao.cqbc.yqCarrierManage.domain.YqCarrierManage;
import cn.yuanqiao.cqbc.yqCarrierManage.mapper.YqCarrierManageMapper;
import cn.yuanqiao.cqbc.yqSetPlate.domain.YqSetPlateRule;
import cn.yuanqiao.cqbc.yqSetPlate.exception.SetPlateRuleException;
import cn.yuanqiao.cqbc.yqSetPlate.mapper.YqSetPlateRuleMapper;
import cn.yuanqiao.cqbc.yqSetPlate.service.YqSetPlateRuleService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * <p>
 * 组盘规则表 服务实现类
 * </p>
 *
 * @author lyk
 * @since 2022-11-22
 */
@Service
public class YqSetPlateRuleServiceImpl implements YqSetPlateRuleService {

    //@Resource
    //MapperToolsMapper DbTool;

    //@Resource
    //private DictMapper sysDictDao;
    @Autowired
    private YqSetPlateRuleMapper yqSetPlateRuleMapper;
    @Autowired
    private YqCarrierManageMapper yqCarrierManageMapper;
    @Resource
    private MapperToolsMapper DbTool;
    //@Resource
    //private YqCarrierManageMapper yqCarrierManageMapper;

    @Override
    public int add(YqSetPlateRule param){
        String tenantCode = SecurityUtils.getTenantCode();
        param.setTenantCode(tenantCode);
        return yqSetPlateRuleMapper.add(param);
        //YqSetPlateRule entity = getEntity(param);
        //this.save(entity);
    }

    @Override
    public int delete(Long id){
        return yqSetPlateRuleMapper.delete(id);
        //this.removeById(getKey(param));
    }

    @Override
    public int update(YqSetPlateRule param){
        return yqSetPlateRuleMapper.update(param);
        /*YqSetPlateRule oldEntity = getOldEntity(param);
        YqSetPlateRule newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);*/
    }

    public YqSetPlateRule getById(Long id){
        return yqSetPlateRuleMapper.getById(id);
    }

    @Override
    public YqSetPlateRule findBySpec(YqSetPlateRule param){
        return null;
    }

    @Override
    public List<YqSetPlateRule> findListBySpec(YqSetPlateRule param){
        return null;
    }

   /* @Override
    public Map<String,Object> getAddData(YqSetPlateRule param){
        //this.baseMapper.getAllDataNeed();
        List<Map<String, Object>> listResultCategory = DbTool.getListResult("SELECT * FROM YQ_HDDACATEGORY WHERE TYPE = 'f' OR TYPE = 'v';");
        List<Map<String, Object>> listResultFonds = DbTool.getListResult("SELECT * FROM YQ_HDFONDS;");
        List<Map<String, Object>> BGQX = sysDictDao.loadSysDictByCode("BGQX");
        List<Map<String, Object>> MJ = sysDictDao.loadSysDictByCode("MJ");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("category",listResultCategory);
        hashMap.put("fonds", listResultFonds);
        hashMap.put("bgqx",BGQX);
        hashMap.put("mj",MJ);

        return hashMap;
    }*/

    @Override
    public List<String> findBySetPlant(YqSetPlateRule item) {
//baseMapper.customList()
        String[] split = item.getBgqx().split(",");
        StringBuffer bgqxStr = new StringBuffer();
        for (String s : split) {
            bgqxStr.append('\'').append(s).append('\'').append(',');
        }
        String fondsCode = item.getFondsCode();
        StringBuffer qzhStr = new StringBuffer();
        if(fondsCode !=null && fondsCode != ""){
            String[] split1 = fondsCode.split(",");
            for(String s : split1){
                qzhStr.append('\'').append(s).append('\'').append(',');
            }

        }
        String mj = item.getMj();
        StringBuffer mjStr = new StringBuffer();
        if(mj!=null && mj !=""){
            String[] split1 = mj.split(",");
            for(String s : split1){
                mjStr.append('\'').append(s).append('\'').append(',');
            }
        }
        String substring = bgqxStr.substring(0, bgqxStr.length() - 1);
        String qzhsubstring = "";
        if(qzhStr!=null){
            qzhsubstring = qzhStr.substring(0, qzhStr.length() - 1);
        }
        String mjsubstring = "";
        if(mjStr!=null){
            mjsubstring = mjStr.substring(0, mjStr.length() - 1);
        }
        //QueryWrapper<DataManage> queryWrapper = new QueryWrapper<>();
        //queryWrapper.inSql("id","SELECT DATA_ID FROM YQ_HDDA WHERE BGQX IN("+substring+
        //        ") AND ND <="+item.getEndTime()+" AND ND >="+ item.getStartYear()+" AND DAQZH IN("+qzhsubstring+")"+
        //        " AND MJ IN ("+mjsubstring+") AND CATEGORY_ID in (SELECT ID FROM YQ_HDDACATEGORY WHERE NAME = '"+item.getCategoryName()+"')");
        String tenantCode = SecurityUtils.getTenantCode();
        String sql="SELECT DATA_ID FROM "+tenantCode+"_CQBC_HDDA WHERE BGQX IN("+substring+") AND ND <="+item.getEndTime()+" " +
                "AND ND >="+ item.getStartYear()+" AND QZH IN("+qzhsubstring+")"+ " AND MJ IN ("+mjsubstring+") " +
                "AND CATEGORY_ID in (SELECT ID FROM "+tenantCode+"_CATEGORY WHERE NAME = '"+item.getCategoryName()+"') AND " +
                "(IS_ZUPAN IS NULL OR IS_ZUPAN ='')  AND IS_DEL=0";
        List<String> sql1 = DbTool.getSingleListBySql(sql);
        System.out.println("sql::" + sql1);
        //baseMapper.selectList()
        //this.baseMapper.selectList(queryWrapper)
        return sql1;


    }

    @Override
    public List<YqSetPlateRule> findPageBySpec(YqSetPlateRule param){
        //Page pageContext = getPageContext();
        //IPage page = this.baseMapper.customPageList(pageContext, param);
        PageUtils.startPage();
        String tenantCode = SecurityUtils.getTenantCode();
        param.setTenantCode(tenantCode);
        List<YqSetPlateRule> list=yqSetPlateRuleMapper.customList(param);
        for(int i=0;i<list.size();i++){
            YqSetPlateRule YqSetPlateRule=list.get(i);
            String mj=YqSetPlateRule.getMj();
            String newMJ="";
            if(mj!=null&&!"".equals(mj)){
               if(mj.indexOf(",")>-1){
                 String [] mjArr=mj.split(",");
                 for(int j=0;j<mjArr.length;j++){
                     newMJ+=DbTool.getSingle("select dict_label from "+tenantCode+"_DICT_DATA WHERE DICT_TYPE = 'MJ' and dict_value = '"+mjArr[j]+"'")+",";
                     //newMJ+=sysDictDao.getNameByCode("MJ",mjArr[j])+",";
                 }
               }else{
                   newMJ=DbTool.getSingle("select dict_label from "+tenantCode+"_DICT_DATA WHERE DICT_TYPE = 'MJ' and dict_value = '"+mj+"'");
                   //newMJ=sysDictDao.getNameByCode("MJ",mj);
               }
             if(newMJ.indexOf(",")>-1){
                 newMJ=newMJ.substring(0,newMJ.length()-1);
             }
             YqSetPlateRule.setMj(newMJ);
            }
            //list.set(i,YqSetPlateRule);
            String fondsCode=YqSetPlateRule.getFondsCode();
            String newFonds="";
            if(fondsCode!=null&&!"".equals(fondsCode)){
                if(fondsCode.indexOf(",")>-1){
                    String [] fondsCodeArr=fondsCode.split(",");
                    for(int j=0;j<fondsCodeArr.length;j++){
                        //newFonds+=baseMapper.getFonds(fondsCodeArr[j])+",";
                        newFonds+=DbTool.getSingle("select fonds_name from manage_fonds where tenantcode = '"+tenantCode+"' and fonds_code = '"+fondsCodeArr[j]+"'")+",";
                    }
                }else{
                    //newFonds=baseMapper.getFonds(fondsCode);
                    newFonds=DbTool.getSingle("select fonds_name from manage_fonds where tenantcode = '"+tenantCode+"' and fonds_code = '"+fondsCode+"'");
                }
                if(newFonds!=null&&newFonds.indexOf(",")>-1){
                    newFonds=newFonds.substring(0,newFonds.length()-1);
                }
                YqSetPlateRule.setFondsCode(newFonds);
            }
        }
        //page.setRecords(list);
        return list;
    }

    /**
     *
     * @param yqDataManageList 档案数据
     * @param size byte字节数
     * @param count 数量
     * @return
     */
    /*@Override
    public List<List<Archives>> getPageDate(List<Archives> yqDataManageList, String size, String count) throws SetPlateRuleException {
        //TODO 执行分页逻辑
        long sizeLong = Long.valueOf(size);
        long countLong = Long.valueOf(count);
        System.out.println(222);
        List<List<Archives>> result = new LinkedList<>();
        int i = 0;
        String errorMsg = "";
        long resSizeLong = Long.valueOf(size);
        long resCountLong = Long.valueOf(count);
        List<Archives> archives = new LinkedList<>();
        for (Archives item : yqDataManageList) {
            //List<Archives> archives = new LinkedList<>();
            Long eepSize = Long.valueOf(item.getEepSize());
            if (eepSize>sizeLong){
                errorMsg+="档案"+item.getDh()+"的大小超过盘本身规格；";
                continue;
            }else {
                resSizeLong = resSizeLong - eepSize;
                //剩余盘空间不足
                if (resSizeLong <= 1024 && resCountLong >= 1){
                    resCountLong -= 1;
                    resSizeLong = sizeLong;
                    result.add(archives);
                    archives = new LinkedList<>();
                    archives.add(item);
                }else if (resSizeLong <= 1024 && resCountLong <1){
                    errorMsg += "剩余盘空间不足；";
                    break;
                }else {
                    archives.add(item);
                }
            }
        }
        //List<Archives> archives = new LinkedList<>();
        *//*archives = yqDataManageList.subList(i,yqDataManageList.size());
        result.add(archives);*//*
        result.add(archives);
        if (!"".equals(errorMsg)){
            throw new SetPlateRuleException(errorMsg);
        }
        return result;
    }*/

    @Override
    public List<List<DataManage>> getPageDateZip(List<DataManage> yqDataManageList, String size, String count) throws SetPlateRuleException {
        //TODO 执行分页逻辑
        Double sizeLong = Double.valueOf(size);
        Double countLong = Double.valueOf(count);
        List<List<DataManage>> result = new LinkedList<>();
        int i = 0;
        String errorMsg = "";
        Double resSizeLong = Double.valueOf(size);
        Double resCountLong = Double.valueOf(count);
        List<DataManage> archives = new LinkedList<>();
        for (DataManage item : yqDataManageList) {
            //List<Archives> archives = new LinkedList<>();
            Long eepSize = Long.valueOf(item.getSize());
            if (eepSize>sizeLong){
                errorMsg+="档案"+item.getDh()+"的大小超过盘本身规格；";
                continue;
            }else {
                resSizeLong = resSizeLong - eepSize;
                //剩余盘空间不足
                if (resSizeLong <= 1024 && resCountLong >= 1){
                    resCountLong -= 1;
                    resSizeLong = sizeLong;
                    result.add(archives);
                    archives = new LinkedList<>();
                    archives.add(item);
                }else if (resSizeLong <= 1024 && resCountLong <1){
                    errorMsg += "剩余盘空间不足；";
                    break;
                }else {
                    archives.add(item);
                }
            }
        }
        //List<Archives> archives = new LinkedList<>();
        /*archives = yqDataManageList.subList(i,yqDataManageList.size());
        result.add(archives);*/
        result.add(archives);
        if (!"".equals(errorMsg)){
            throw new SetPlateRuleException(errorMsg);
        }
        return result;
    }



    @Override
    public boolean moveFileToPath(String newFile,String newPath){
        boolean flag = false;
        File startFile=new File(newFile);
        File endDirection=new File(newPath);
        if(!endDirection.exists()) {
            endDirection.mkdirs();
        }
        File endFile=new File(endDirection+ File.separator+ startFile.getName());
        try {
            if (startFile.renameTo(endFile)) {
                System.out.println("文件移动成功！目标路径：{"+endFile.getAbsolutePath()+"}");
                flag = true;
            } else {
                System.out.println("文件移动失败！起始路径：{"+startFile.getAbsolutePath()+"}");
            }
        }catch(Exception e) {
            System.out.println("文件移动出现异常！起始路径：{"+startFile.getAbsolutePath()+"}");
        }
        return flag;
    }

    @Override
    public List<TreeSelect> tree() {
        YqCarrierManage yqCarrierManage = new YqCarrierManage();
        String tenantCode = SecurityUtils.getTenantCode();
        yqCarrierManage.setTenantCode(tenantCode);
        List<YqCarrierManage> yqCarrierManages = yqCarrierManageMapper.customList(yqCarrierManage);
        TreeSelect rootTree = new TreeSelect();
        rootTree.setId(0L);
        rootTree.setLabel("载体");
        rootTree.setNodeType("root");
        List<TreeSelect> chilTrees = new ArrayList<>();
        for (YqCarrierManage mf : yqCarrierManages) {
            TreeSelect chilTree = new TreeSelect();
            chilTree.setId(mf.getId());
            chilTree.setLabel(mf.getName());
            //chilTree.setFondsCode(mf.getFondsCode());
            chilTree.setTenantCode(mf.getTenantCode());
            chilTree.setNodeType("Carrier");
            chilTrees.add(chilTree);
        }
        rootTree.setChildren(chilTrees);
        List<TreeSelect> treeSelects = new ArrayList<>();
        treeSelects.add(rootTree);
        return treeSelects;



        //return yqCarrierManageMapper.carrierTreeList();
    }

    @Override
    public boolean copyFileToPath(String newFile,String newPath){
        boolean flag = false;
        File startFile=new File(newFile);
        File endDirection=new File(newPath);
        if(!endDirection.exists()) {
            endDirection.mkdirs();
        }
        File endFile=new File(endDirection+ File.separator+ startFile.getName());
        try {
            FileUtils.copyFile(startFile,endFile);
            flag = true;
         /*   if () {
                System.out.println("文件移动成功！目标路径：{"+endFile.getAbsolutePath()+"}");

            } else {
                System.out.println("文件移动失败！起始路径：{"+startFile.getAbsolutePath()+"}");
            }*/
        }catch(Exception e) {
            flag = false;
            System.out.println("文件移动出现异常！起始路径：{"+startFile.getAbsolutePath()+"}");
        }
        return flag;
    }

}
